﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EIS_desktop
{
    public partial class NewPayRoll : Form
    {
        enum PayRollColumnName
        {
            EmpID = 0, StartDate, EndDate, PayDate, Percentage, ClientRate,
            ActualRate, PaidRate, Difference, HoursWorkedCurrentMonth, HoursPaidWithHold, TotalHoursPaid,
            CurrentMonthWithHoldAmount, WithHoldBalanceForward, SalaryFromWithHold, PerDiem_otherPayWithHeld,
            BalanceWithHeldAmount, FilingFeeDeduction, OtherAdjustment, Total, RequireWithHodling

        }

        #region fields
        private string _month, _name;
        public static double _balance;
        private int _year, _id;
        bool rowedited = false;
        bool newrowadded = false;
        private bool IsLoading;
        int rownumer = -1;
        DataTable dt;
        System.Data.SqlClient.SqlDataAdapter sqladp;
        #endregion

        #region properties
        /// <summary>
        /// Name of Employee
        /// </summary>
        public string EmployeeName
        {
            get { return _name; }
        }
        /// <summary>
        /// Id of Employee from Employee table
        /// </summary>
        public int EmployeeId
        {
            get { return _id; }
        }
        /// <summary>
        /// Month selected
        /// </summary>
        public string Month
        {
            get { return _month; }
        }

        /// <summary>
        /// Year selected
        /// </summary>
        public int Year
        {
            get { return _year; }
        }

        public double WithHeldBalanceForward
        {
            get
            {
                try
                {
                    string datestr = "1-" + Month + "-" + Year.ToString();
                    System.Data.SqlClient.SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
                    System.Data.SqlClient.SqlCommand sqlcmd = new System.Data.SqlClient.SqlCommand("select count(*) from PayRoll where Empid = " + EmployeeId, sqlcon);

                    sqlcon.Open();
                    int count = sqlcmd.ExecuteNonQuery();
                    sqlcon.Close();

                    if (count > 0)
                    {
                        sqlcmd = new System.Data.SqlClient.SqlCommand
                           ("Select BalanceWithHeldAmount from PayRoll where EmpId= " + EmployeeId +
                           " and PayPeriod = dateadd(m,-1,'" + datestr + "')", sqlcon);
                        sqlcon.Open();
                        _balance = Convert.ToDouble(sqlcmd.ExecuteScalar());
                        sqlcon.Close();
                    }
                    else
                    {
                        sqlcmd = new System.Data.SqlClient.SqlCommand("select intialbalance from BalanceIntialize where empId = " + EmployeeId, sqlcon);
                        sqlcon.Open();
                        _balance = Convert.ToDouble(sqlcmd.ExecuteScalar());
                        sqlcon.Close();

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                return _balance;
            }
        }
        #endregion
        public NewPayRoll( )
        {
            InitializeComponent();
        }
        public NewPayRoll(string month, int year, int empid, string name)
        {
            _name = name;
            _id = empid;
            _month = month;
            _year = year;
            InitializeComponent();
        }

        public double InitialBalance
        {
            get
            {
                try
                {
                    _balance = 0;
                    string datestr = "1-" + Month + "-" + Year.ToString();
                    System.Data.SqlClient.SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
                    System.Data.SqlClient.SqlCommand sqlcmd = new System.Data.SqlClient.SqlCommand("select count(*) from AdvPayRoll where Empid = " + EmployeeId, sqlcon);

                    sqlcon.Open();
                    int count = sqlcmd.ExecuteNonQuery();
                    sqlcon.Close();

                    if (count <= 0)
                    {
                        sqlcmd = new System.Data.SqlClient.SqlCommand("select intialbalance from BalanceIntialize where empId = " + EmployeeId, sqlcon);
                        sqlcon.Open();
                        _balance = Convert.ToDouble(sqlcmd.ExecuteScalar());
                        sqlcon.Close();

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                return _balance;
            }
        }
        private void NewPayRoll_Load(object sender, EventArgs e)
        {

            string datestr = "1-" + Month + "-" + Year.ToString();
            System.Data.SqlClient.SqlConnection sqlcon = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings["constr"]);
            System.Data.SqlClient.SqlCommand sqlcmd =
                new System.Data.SqlClient.SqlCommand("SELECT EmpID, StartDate, EndDate, PayDate, Percentage, ClientRate," +
                    "ActualRate, PaidRate, Difference, HoursWorkedCurrentMonth, HoursPaidWithHold, TotalHoursPaid," +
                     " CurrentMonthWithHoldAmount, WithHoldBalanceForward, SalaryFromWithHold, PerDiem_otherPayWithHeld," +
                     " BalanceWithHeldAmount, FilingFeeDeduction, OtherAdjustment, Total, RequireWithHodling" +
                    " FROM AdvPayroll where Year(StartDate)= " + Year + " and Left(Datename(m,StartDate),3) = '" + Month + "'"
                    + " and EmpID =" + EmployeeId
                    + " order by EmpId,StartDate asc", sqlcon);

            dt = new DataTable();
            sqladp = new System.Data.SqlClient.SqlDataAdapter(sqlcmd);
            sqladp.Fill(dt);
            //dt.PrimaryKey = new DataColumn[] { dt.Columns[0], dt.Columns[1], dt.Columns[2] };
            System.Data.SqlClient.SqlCommandBuilder sqlcmb = new System.Data.SqlClient.SqlCommandBuilder(sqladp);
            //sqladp.InsertCommand = sqlcmb.GetInsertCommand();
            //sqladp.DeleteCommand = new System.Data.SqlClient.SqlCommand("DELETE FROM AdvPayroll WHERE (EmpID = @empid) AND "
            // + "(StartDate = @startdate) AND (EndDate = @enddate)");
            // sqladp.UpdateCommand = sqlcmb.GetUpdateCommand();


            dataGridView1.DataSource = dt;
            //dataGridView1.Columns["EmpID"].Visible = false;
            //dataGridView1.Columns.Remove("StartDate");
            //dataGridView1.Columns.Remove("EndDate");
            //CalendarColumn col = new CalendarColumn();
            //col.Name = "StartDate";
            //dataGridView1.Columns.Insert(1, col);
            //col = new CalendarColumn();
            //col.Name = "EndDate";
            //dataGridView1.Columns.Insert(2, col);
            dataGridView1.Columns["StartDate"].DefaultCellStyle.Format = "dd-MMM-yyyy";
            dataGridView1.Columns["EndDate"].DefaultCellStyle.Format = "dd-MMM-yyyy";

            //dataGridView1.Columns.Remove("Percentage");
            //DataGridViewComboBoxColumn dgvcombocol = new DataGridViewComboBoxColumn();
            //dgvcombocol.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
            //dgvcombocol.Items.AddRange("70","75","80");
            //dataGridView1.Columns.Insert(4, dgvcombocol);
            //dataGridView1.Columns[4].DataPropertyName = "Percentage";

            //for (int count = 0; count < dt.Rows.Count; count++)
            //{
            //    DataRow dr = dt.Rows[count];
            //    try
            //    {
            //        dataGridView1.Rows[count].Cells["StartDate"].Value = dr["StartDate"];
            //        dataGridView1.Rows[count].Cells["EndDate"].Value = dr["EndDate"];
            //        //dataGridView1.Rows[count].Cells["Percentage"].Value = dr["Percentage"];
            //    }
            //    catch { }
            //}

         
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == (int)PayRollColumnName.Percentage)
            {
                DataGridViewComboBoxCell combocell = new DataGridViewComboBoxCell();
                combocell.Items.AddRange("70", "75", "80");
                dataGridView1[e.ColumnIndex,e.RowIndex] = combocell;
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            DataGridView dgv = dataGridView1;
            DataGridViewRow dgvrow = dgv.Rows[e.RowIndex];
            this.Text = "finished editiing";
            DateTime  datestr =Convert.ToDateTime("1-" + Month + "-" + Year.ToString());
            try
            {
                switch (dataGridView1.Columns[e.ColumnIndex].Name)
                {

                    case "StartDate":
                        if (DateTime.Compare((DateTime)dgvrow.Cells["StartDate"].Value, datestr) == -1)
                            dgvrow.Cells["StartDate"].ErrorText = "date should not be earlier than " + datestr.ToString();
                        else
                            dgvrow.Cells["StartDate"].ErrorText = string.Empty;
                            if (e.RowIndex > 0)
                            if (DateTime.Compare((DateTime)dgvrow.Cells["StartDate"].Value, (DateTime)dataGridView1.Rows[e.RowIndex - 1].Cells["EndDate"].Value) == -1)
                            {
                                dgvrow.Cells["StartDate"].ErrorText = "Start Date should be earlier that previous endDate";
                            }
                            else
                                dgvrow.Cells["StartDate"].ErrorText = string.Empty;
                        break;
                    case "EndDate":
                        if (DateTime.Compare((DateTime)dgvrow.Cells["EndDate"].Value, datestr) == -1)
                            dgvrow.Cells["EndDate"].ErrorText = "date should not be realier than " + datestr.ToString();
                        else
                            dgvrow.Cells["EndDate"].ErrorText = string.Empty;
                        if (DateTime.Compare((DateTime)dgvrow.Cells["EndDate"].Value, (DateTime)dataGridView1.Rows[e.RowIndex].Cells["StartDate"].Value) == -1)
                        {
                            dgvrow.ErrorText = "End Date should be later that start Date";
                        }
                        else
                            dgvrow.ErrorText = string.Empty;
                        break;
                    case "ClientRate":
                        dgv.Rows[e.RowIndex].Cells[(int)PayRollColumnName.ActualRate].Value =
                        (Convert.ToInt32(dgv.Rows[e.RowIndex].Cells[(int)PayRollColumnName.Percentage].Value) *
                          (double)dgv.Rows[e.RowIndex].Cells[(int)PayRollColumnName.ClientRate].Value) / 100;


                        break;
                    case "PaidRate":

                        dgv.Rows[e.RowIndex].Cells[(int)PayRollColumnName.Difference].Value =
                            (double)dgv.Rows[e.RowIndex].Cells[(int)PayRollColumnName.ActualRate].Value -
                            (double)dgv.Rows[e.RowIndex].Cells[(int)PayRollColumnName.PaidRate].Value;

                        break;
                    case "HoursPaidWithHold":

                        dgvrow.Cells[(int)PayRollColumnName.TotalHoursPaid].Value =
                            (int)dgvrow.Cells[(int)PayRollColumnName.HoursWorkedCurrentMonth].Value +
                            (int)dgvrow.Cells[(int)PayRollColumnName.HoursPaidWithHold].Value;
                        dgvrow.Cells[(int)PayRollColumnName.CurrentMonthWithHoldAmount].Value =
                            (double)dgvrow.Cells[(int)PayRollColumnName.Difference].Value +
                            (int)dgvrow.Cells[(int)PayRollColumnName.HoursWorkedCurrentMonth].Value;
                        if (e.RowIndex > 0)
                            dgvrow.Cells[(int)PayRollColumnName.WithHoldBalanceForward].Value =
                          dataGridView1.Rows[e.RowIndex - 1].Cells[(int)PayRollColumnName.BalanceWithHeldAmount].Value;
                        dgvrow.Cells[(int)PayRollColumnName.SalaryFromWithHold].Value =
                            (double)dgvrow.Cells[(int)PayRollColumnName.PaidRate].Value *
                            (int)dgvrow.Cells[(int)PayRollColumnName.HoursPaidWithHold].Value;
                        break;
                    case "PerDiem_otherPayWithHeld":
                        double amount =0.0;
                        if (dgvrow.Cells[(int)PayRollColumnName.CurrentMonthWithHoldAmount].Value != DBNull.Value)
                            amount +=(double)dgvrow.Cells[(int)PayRollColumnName.CurrentMonthWithHoldAmount].Value;
                        if (dgvrow.Cells[(int)PayRollColumnName.WithHoldBalanceForward].Value != DBNull.Value)
                            amount +=(double)(dgvrow.Cells[(int)PayRollColumnName.WithHoldBalanceForward].Value);
                        if (dgvrow.Cells[(int)PayRollColumnName.SalaryFromWithHold].Value !=DBNull.Value)
                            amount -= (double)(dgvrow.Cells[(int)PayRollColumnName.SalaryFromWithHold].Value);
                        if (dgvrow.Cells[(int)PayRollColumnName.PerDiem_otherPayWithHeld].Value !=DBNull.Value)
                            amount -= (double)(dgvrow.Cells[(int)PayRollColumnName.PerDiem_otherPayWithHeld].Value);
                         dgvrow.Cells[(int)PayRollColumnName.BalanceWithHeldAmount].Value = amount; 
                         break;
                    case "OtherAdjustment":
                        dgvrow.Cells[(int)PayRollColumnName.Total].Value =
                        (double)(dgvrow.Cells[(int)PayRollColumnName.BalanceWithHeldAmount].Value??0.0) -
                       (double)(dgvrow.Cells[(int)PayRollColumnName.OtherAdjustment].Value??0.0);
                        break;
                }
            }
            catch
            {
                throw;
            }
         
           
        }

        private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {

            DataGridViewRow dgvrow = dataGridView1.CurrentRow;
            rownumer = dgvrow.Index;
            newrowadded = true;
            dgvrow.Cells[(int)PayRollColumnName.WithHoldBalanceForward].Value = InitialBalance;
            if (e.Row.Index > 0)
            {
                dgvrow.Cells[(int)PayRollColumnName.WithHoldBalanceForward].Value = dataGridView1.Rows[e.Row.Index - 1].Cells[(int)PayRollColumnName.BalanceWithHeldAmount].Value;
            }
            dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
            dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (newrowadded == true)
            {
                dt = dt.GetChanges(DataRowState.Added);
                sqladp.Update(dt);
                newrowadded = false;
            }
            if (rowedited == true)
            {

            }

        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            
        }


    }
}
